<template>
	<view class="container">
		<view class="login_box" v-if="!token">
			<view class="login_title">您还未登录</view>
			<view class="login_content">
				请先登录之后再进行操作!
			</view>
			<view class="login_but_group">
				<button type="default" size="default" @click="back">暂不登录</button>
				<button type="warn" size="default" @click="getUserInfoProfile">立即登录</button>
			</view>
		</view>
		<!--v-if="token&&(!userInfo.phone||userInfo.nickname=='微信用户')" -->
		<view class="authorization" v-if="token&&(!userInfo.phone||userInfo.nickname=='微信用户')">
			<uni-popup ref="popup" type="bottom" background-color="#fff">
				<view class="popup-content">
					<view class="hint">
						用户选择使用微信头像和昵称便于发货
					</view>
					<view class="acquire">
						<view class="item">
							<!-- @chooseavatar="onChooseAvatar" -->
							<button class="more_but" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"  :plain="true"
								type="default">
								<view class="dislpay_box">
									<image :src="avatarUrl" mode="aspectFit" />
									<!-- @click="handleAva" -->
									<!-- <u-avatar  class="avatar" size="80" :src="avatarUrl"></u-avatar> -->
								</view>
								<!-- <text class="iconfont icon-jiantou"></text> -->
							</button>
						</view>
						<view class="item">
							<text>昵称：</text>
							<view class="flex">
								<input class="input_field" type="nickname" v-model="userName" placeholder="点击获取或输入昵称" />
							</view>

						</view>
						<view class="item">
							<text>手机号：</text>
							<view class="flex">
								<button class="input_field" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
									<text v-if="phone">{{phone}}</text>
									<text class="stress" v-else>点击获取手机号</text>
								</button>
							</view>

						</view>
					</view>
					<button class="mini-btn" type="warn" @click="authorizationClick">立即登录</button>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex'
	import {
		wxappAuth,
		getUser,
		wxappBindingPhone,
		updateNameAndAvatar,
		getUserInfo
	} from '@/api/user'
	import dayjs from 'dayjs'
	import cookie from '@/utils/store/cookie'
	import {
		login,
		authorize
	} from '@/utils'
	import {
		VUE_APP_API_URL
	} from '@/config'
	// import store from '@/store'
	export default {
		data() {
			return {
				authorize: false,
				canIUseGetUserProfile: false,
				userAgreement: true,
				// 头像地址
				avatarUrl: "",
				// 昵称
				userName: "",
				// 手机号
				phone: ""
			}
		},
		computed: {
			...mapState(['isAuthorization', '$deviceType', 'token']),
			...mapGetters(["userInfo", 'token']),
		},
		onLoad() {
			if (wx.getUserProfile) {
				this.canIUseGetUserProfile = true
			}
			// // 先校验用户是否授权，如果没有授权，显示授权按钮
			console.log("onLoad")
		},
		onHide() {
			this.updateAuthorizationPage(false)
			this.changeAuthorization(false)
			console.log("onHide")
		},
		onUnload() {
			this.updateAuthorizationPage(false)
			this.changeAuthorization(false)
			console.log("onUnload")
		},
		methods: {
			...mapActions(['changeAuthorization', 'setUserInfo']),
			...mapMutations(['updateAuthorizationPage']),
			monitorCheckbox(e) {
				let agreement = e.detail.value;
				if (agreement == 'agree') {
					this.userAgreement = true
				} else {
					this.userAgreement = false
				}
			},
			back() {
				console.log("back返回")
				this.$parent.closeLogin()
			},
			getUserInfo(data) {
				if (data.detail.errMsg == 'getUserInfo:fail auth deny') {
					uni.showToast({
						title: '取消授权',
						icon: 'none',
						duration: 2000,
					})
					return
				}
				uni.showLoading({
					title: '登录中',
				})
				login()
					.then(e => {
						uni.hideLoading()
					})
					.catch(error => {
						uni.hideLoading()
						uni.showToast({
							title: error,
							icon: 'none',
							duration: 2000,
						})
					})
			},
			getUserInfoProfile(data) {
				if (!this.userAgreement) {
					uni.showToast({
						title: '请勾选用户及隐私协议',
						icon: 'none',
						duration: 2000,
					})
					return
				}
				wx.getUserProfile({
					lang: 'zh_CN',
					desc: '需要获取您的信息用来展示',
					success: res => {
						uni.showLoading({
							title: '登录中',
						})
						login(res)
							.then(e => {
								this.getBasicInfo()
								// debugger
								// // TODO
								// this.$refs.popup.open()
								// return
								if (this.userInfo.phone == '' || this.userInfo.phone == null || !this
									.userInfo.nickname || this.userInfo.nickname == '微信用户') {
									this.$nextTick(() => {
										this.$refs.popup.open()
									})
									return
								} else {
									// #ifdef H5
									this.$yrouter.reLaunch({
										path: cookie.get('redirect').replace(/\ /g, ''),
									})
									// #endif

									// #ifdef MP-WEIXIN

									let pages = getCurrentPages()
									let currentPage = pages[pages.length - 1] //获取当前页面的对象
									let url = currentPage.route //当前页面url
									// if (url === 'pages/user/User/index') {
									// 	this.$parent.updateDate()
									// 	// this.$yrouter.reLaunch({
									// 	// 	path: cookie.get('redirect').replace(/\ /g, ''),
									// 	// })
									// }
									this.$store.dispatch('getUser')
									this.back()
									//  else if (url === 'pages/authorization/index') {
									// 	this.$yrouter.reLaunch({
									// 		path: "/pages/Loading/index"
									// 	});
									// }
									// #endif
								}
								uni.hideLoading()
							})
							.catch(error => {
								uni.hideLoading()
								uni.showToast({
									title: error,
									icon: 'none',
									duration: 2000,
								})
							})
					},
				})
			},
			getPhoneNumber: function(e) {
				let thit = this
				// 判断一下这里是不是小程序 如果是小程序，走获取微信手机号进行绑定
				if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
					uni.showLoading({
						title: '绑定中',
					})
					wxappBindingPhone({
							encryptedData: e.mp.detail.encryptedData,
							iv: e.mp.detail.iv,
						})
						.then(res => {
							uni.hideLoading()
							const data = res.data || {}
							this.phone = data.phone || ""
						})
						.catch(error => {
							const data = error.data || {}
							uni.hideLoading()
							if (data.status != 5101) {
								this.phone = ""
							}
							uni.showToast({
								title: error.msg || error.response.data.msg || error.response.data.message,
								icon: 'none',
								duration: 2000,
							})
						})
				} else {
					thit.phone = ""
					uni.showToast({
						title: '已拒绝授权',
						icon: 'none',
						duration: 2000,
					})
				}
			},
			// 获取用户中的手机号、头像、昵称
			getBasicInfo() {
				// 头像
				this.avatarUrl = this.userInfo.avatar
				// 昵称
				this.userName = this.userInfo.nickname
				// 手机号
				this.phone = this.userInfo.phone
			},
			// 头像信息
			onChooseAvatar(e) {
				console.log('11111111111111111111111111111', e)
				const detail = e.detail || {};
				// return
				uni.uploadFile({
					url: `${VUE_APP_API_URL}/api/upload`,
					// file: image,
					filePath: detail.avatarUrl,
					header: {
						Authorization: 'Bearer ' + this.token,
					},
					name: 'file',
					success: res => {
						if (res) {
							const data = JSON.parse(res.data)
							this.avatarUrl = data.link;
						}
					},
					fail: err => {
						uni.showToast({
							title: '获取头像失败',
							icon: 'none',
							duration: 2000,
						})
					},
					// complete: res => {
					// 	uni.hideLoading()
					// },
				})
			},
			// 确认授权
			authorizationClick() {
				let hint = ""
				if (!this.userName || this.userName == '微信用户') {
					hint = '请修改用户昵称'
				} else if (!this.phone) {
					hint = '手机号暂未授权，请先授权'
				}
				if (hint) {
					uni.showToast({
						title: hint,
						icon: 'none',
						duration: 2000,
					})
					return
				}
				uni.showLoading({
					title: '登录中',
				})
				const option = {
					avatar: this.avatarUrl,
					nickname: this.userName,
					phone: this.phone
				}
				updateNameAndAvatar(option).then(res => {
						uni.hideLoading()
						if (res.status == 200) {
							this.$store.dispatch('getUser')
							this.back()
						}
					})
					.catch(error => {
						uni.hideLoading()
					})
			}
		},
		mounted() {
			if (wx.getUserProfile) {
				this.canIUseGetUserProfile = true
			}
			this.getBasicInfo()
			console.log("mounted", this.token)
			// this.$refs.popup.open()
		},
	}
</script>

<style lang="less">
	.container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.login_box {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: white;
		border-radius: 15rpx;
		width: 85%;
		padding:30rpx 10rpx 20rpx 10rpx;

		.login_title {
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
			color: #383838;
			margin-top: 10rpx;
		}

		.login_content {
			text-align: center;
			color: #676767;
			margin: 20rpx 0;
			padding: 10rpx;
		}

		.login_but_group {
			display: flex;
			align-items: center;
			justify-content: space-around;
			// padding: 10rpx 0;
			margin: 30rpx 0;
			button{
			margin-left: 0;
			margin-right: 0;
			}
		}
	}

	.authorization {
		height: 100%;
		width: 100%;

		.uni-transition {
			background-color: white;
		}

		.popup-content {
			padding: 20rpx 20rpx 0;

			.hint {
				padding: 10rpx;
				color: #ABABAB;
				font-size: 25rpx;
			}

			.acquire {
				margin: 20rpx 0 30rpx 0;

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					margin: 20rpx 0;

					text {
						width: 150rpx;
					}

					.more_but {
						padding: 0;
						width: 120rpx;
						height: 120rpx;
						// width: 100%;
						// height: 100%;
						border: none;

						.dislpay_box {
							width: 100%;
							height: 100%;
							// width: 120rpx;
							// height: 120rpx;
							border-radius: 50%;
							background-color: #EDEDED;

							image {
								height: 100%;
								width: 100%;
								border-radius: 50%;
							}
						}
					}

					.flex {
						margin-left: 10rpx;
						flex: 1;
						overflow: hidden;

						.stress {
							color: #ED4E55;
						}
					}

					.input_field {
						width: 100%;
						padding: 0 20rpx;
						border-radius: 20rpx;
						height: 80rpx;
						background-color: #EDEDED;
					}
				}

			}

			.mini-btn {
				width: 90%;
				margin-bottom: 20rpx;
			}
		}
	}
</style>